package com.bulletelc.apollopre.module.display.product.resultList.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.SearchResultGoodsBean;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.module.display.product.details.ProductDetailsActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CX on 2018/4/19.
 * 搜索结果Fragment
 */

public class ResultListFragment extends MVPBaseFragment<ResultListContact.View, ResultListPresenter>
        implements ResultListContact.View, ProductListAdapter.OnItemClickListener, OnLoadmoreListener {

    // data
    private String keyword; // 关键字
    private String classifyId; // 分类id
    private String sortField = ""; // 排序字段
    private int page = 1; // 当前页，默认第一页
    private int pageCount; // 总页数
    private boolean first = true; // 是否第一次加载

    // views
    private ProgressBar pbLoad;
    private RelativeLayout rlNoData;
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView rvResults;
    private List<SearchResultGoodsBean> productList;
    private ProductListAdapter adapter;
    RecyclerView.LayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2); // 两排布局
    RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); // 垂直布局

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        fragmentShowFirst(hidden);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.result_list_fragment;
    }

    @Override
    public void assignViews() {
        rlNoData = findView(R.id.rlNoData);
        smartRefreshLayout = findView(R.id.smartRefreshLayout);
        rvResults = findView(R.id.rvResults);
        pbLoad = findView(R.id.pbLoad);
    }

    @Override
    public void setListener() {
        smartRefreshLayout.setOnLoadmoreListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            keyword = bundle.getString(IntentCode.EXTRA_KEY_SEARCH_KEYWORD);
            classifyId = bundle.getString(IntentCode.EXTRA_KEY_CLASSIFY_ID);
            sortField = bundle.getString(IntentCode.EXTRA_SORT_PRODUCT_SORT_FIELD);
        }
        productList = new ArrayList<>();
        createDataForLayout(true);
        rvResults.setNestedScrollingEnabled(false);
        smartRefreshLayout.setEnableRefresh(false);//禁止下拉刷新功能
    }

    @Override
    protected ResultListPresenter createPresenter() {
        return new ResultListPresenter();
    }

    @Override
    public void onItemClick(View v, int position) {
        // 跳转详情页
        Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, productList.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void onSuccessByName(List<SearchResultGoodsBean> productList, int totalPage) {
        if (productList != null && productList.size() > 0) {
            this.productList.addAll(productList);
            this.pageCount = totalPage;
            adapter.notifyDataSetChanged();
            rvResults.setVisibility(View.VISIBLE);
            rlNoData.setVisibility(View.GONE);
        } else {
            rvResults.setVisibility(View.GONE);
            rlNoData.setVisibility(View.VISIBLE);
        }
        MyUtil.setProgressBar(pbLoad, false);
        first = false;
    }

    @Override
    public void onFailByName(String fail) {
        ToastUtil.showShortToast(getActivity(), fail);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorByName(String error) {
        ToastUtil.showShortToast(getActivity(), R.string.network_msg);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessByClassifyId(List<SearchResultGoodsBean> productList, int totalPage) {
        if (productList != null && productList.size() > 0) {
            this.productList.addAll(productList);
            this.pageCount = totalPage;
            adapter.notifyDataSetChanged();
            rvResults.setVisibility(View.VISIBLE);
            rlNoData.setVisibility(View.GONE);
        } else {
            rvResults.setVisibility(View.GONE);
            rlNoData.setVisibility(View.VISIBLE);
        }
        MyUtil.setProgressBar(pbLoad, false);
        first = false;
    }

    @Override
    public void onFailByClassifyId(String fail) {
        ToastUtil.showShortToast(getActivity(), fail);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorByClassifyId(String error) {
        ToastUtil.showShortToast(getActivity(), R.string.network_msg);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        if (page <= pageCount) {
            getProductList(page);
        } else {
            // 没有更多数据
        }
        refreshlayout.finishLoadmore(true);
    }

    /**
     * 更换布局
     * @param type True为GridLayout，False为LinearLayout
     */
    public void change(boolean type) {
        createDataForLayout(type);
//        if (type) {
//            rvResults.setLayoutManager(gridLayoutManager);
//        } else {
//            rvResults.setLayoutManager(linearLayoutManager);
//        }
    }

    /**
     * Fragment显示
     * @param hidden
     */
    private void fragmentShowFirst(boolean hidden) {
        if (hidden) {
            return;
        } else {
            if (first) { // 第一次显示
                MyUtil.setProgressBar(pbLoad, true);
                getProductList(page);
            }
        }

    }

    /**
     * 创建视图
     * @param type
     */
    private void createDataForLayout(boolean type) {
        if (type) {
            rvResults.setLayoutManager(gridLayoutManager);
        } else {
            rvResults.setLayoutManager(linearLayoutManager);
        }
        adapter = new ProductListAdapter(getActivity(), productList, type);
        adapter.setOnItemClickListener(this);
        rvResults.setAdapter(adapter);
    }

    /**
     * 获取结果
     * @param page
     */
    private void getProductList(int page) {
        if (keyword != null) {
            presenter.searchByName(page, keyword, sortField);
        } else if (classifyId != null) {
            presenter.searchByClassifyId(page, classifyId, sortField);
        }
    }

    /**
     * 请求排序
     * @param field
     */
    public void sortPrice(String field) {
        MyUtil.setProgressBar(pbLoad, true);
        this.sortField = field;
        productList.clear();
        page = 1;
        getProductList(page);
    }

}
